/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.yzbdl.lanius.orchestrate.serv.utils;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yzbdl.lanius.orchestrate.serv.vo.task.IncrLogVO;
import org.yzbdl.lanius.orchestrate.common.exception.runtime.BusinessException;

/**
 * 文件处理工具类
 *
 * @author JCZ
 * @date 2022-04-21 11:32
 */
public class FileUtil {

    private static final Logger logger = LoggerFactory.getLogger(TaskInstanceLogUtil.class);

    /**
     * 读日志信息
     *
     * @param size
     *        限制行数
     * @param seek
     *        指针位置
     * @param charset
     *        字符集
     * @param absolutePath
     *        绝对路径
     * @return
     *        日志内容
     * @throws IOException
     *         IOException
     */
    public static IncrLogVO readIncrLogs(Long size, Long seek, Charset charset, String absolutePath)
        throws IOException {
        // 设置编码格式
        charset = Objects.isNull(charset) ? Charset.defaultCharset() : charset;

        try (RandomAccessFile rf = new RandomAccessFile(absolutePath, "r")) {
            // 设置本次读取文件内容的指针位置
            rf.seek(seek);
            StringBuilder sb = new StringBuilder();
            for (int lineSeparatorNum = 0; lineSeparatorNum < size; lineSeparatorNum++) {
                // 读取
                String line = rf.readLine();
                if (StringUtils.isNotBlank(line)) {
                    // 编码格式转换
                    String readLine = new String(line.getBytes(StandardCharsets.ISO_8859_1), charset);
                    sb.append(readLine).append("\r\n");
                }
            }
            return IncrLogVO.builder().log(sb.toString()).seek(rf.getFilePointer()).build();
        } catch (Exception e) {
            logger.error("读取实例文件日志出错", e);
            throw new BusinessException("读取实例文件日志出错");
        }
    }

}
